from rest_framework.exceptions import ValidationError
from rest_framework.generics import GenericAPIView, get_object_or_404

from apps.cart.models import Cart
from apps.goods.models import Goods
from apps.order.models import Order, OrderDetail
from apps.order.serializers import OrderSerializer, OrederManySerializer
from utils import ResponseMessage

 
class OrderListGenericAPIView(GenericAPIView):
    serializer_class = OrderSerializer  # 指定序列化器类
    queryset = Order.objects.all()  # 获取查询集
    lookup_fields = ['trade_no']  # 告诉Drf在URL里用什么关键词来找到对应的数据记录（get请求）

    def post(self, request, *args, **kwargs):
        # print(self.get_queryset())
        # print(self.get_serializer())
        data = request.data
        # print(data)
        order = self.get_serializer(data=data)
        if order.is_valid(raise_exception=True):
            # print(order.data)
            order.save()
            return ResponseMessage.OrderResponse.success(order.data)
        else:
            return ResponseMessage.OrderResponse.failed(order.errors)

    def get(self, request, trade_no):
        # if not request.user.get("status"):
        #     return JsonResponse("request.user", safe=False)
        # print(request.data)
        # email = request.user.get("data")
        email = '001@QQ.com'
        print(trade_no)
        # 查询数据库所有数据
        db_result = Order.objects.filter(
            trade_no=trade_no,
            email=email,
            is_delete=0
        ).first()
        res_result = OrederManySerializer(db_result).data
        return ResponseMessage.OrderResponse.success(res_result)

class OrderGenericAPIView(GenericAPIView):
    serializer_class = OrderSerializer
    queryset = Order.objects.all()

    def post(self, request, *args, **kwargs):
        # if not request.user.get("status"):
        #     return JsonResponse("request.user", safe=False)
        # print(request.data)
        # email = request.user.get("data")
        email = '001@QQ.com'
        # user_id = request.data.get('user_id')
        user_id = 1
        import time
        trade_no = int(time.time() * 1000)
        request_data = request.data
        print('------')
        print(request_data)
        trade_data = request_data['trade']
        goods_data = request_data['good']
        print(trade_data)
        print(goods_data)
        trade_data["trade_no"] = trade_no
        trade_data["email"] = email
        trade_data["status"] = 0
        print('------')
        print(trade_data)
        print('------')
        print(goods_data)
        serializer = self.get_serializer(data=trade_data)
        print('序列化完成')
        try:
            if serializer.is_valid():
                print('合法')
                # print(serializer.data)
                serializer.save()
            else:
                raise ValidationError(serializer.errors)
        except ValidationError as e:
            print(e)
            return ResponseMessage.OrderResponse.failed(str(e))
        goods_order_data = {}
        for data in goods_data:
            # 往订单项中添加信息
            goods_order_data["trade_no"] = trade_no

            good = Goods.objects.filter(good_id=data['good']['good_id']).first()
            goods_order_data["goods"] = good
            goods_order_data["num"] = data['num']

            order = Order.objects.filter(trade_no=trade_no).first()
            goods_order_data["order"] = order
            OrderDetail.objects.create(**goods_order_data)
            # 删除购物车项中的信息以及购物车中的信息
            # 先把修改的总金额算出来，方便后面直接使用
            good = get_object_or_404(Goods, good_id=data['good']['good_id'])
            change_price = good.price * data['num']
            cart = Cart.objects.filter(user_id=user_id).first()
            if cart:
                item = cart.item.filter(good=data['good']['good_id']).first()
                # 移除商品
                item.num -= data['num']
                if item.num == 0:
                    item.is_delete = True
                item.save()
                cart.total_goods_number -= data['num']
                cart.total_price -= change_price
                cart.save()
                # return HttpResponse("商品已经从购物车移除")
                return ResponseMessage.OrderResponse.success(serializer.data)


    def get(self, request, *args, **kwargs):
        # if not request.user.get("status"):
        #     return JsonResponse("request.user", safe=False)
        # print(request.data)
        # email = request.user.get("data")
        email = '001@QQ.com'
        print(request.data)
        pay_status = request.GET.get('pay_status')
        if pay_status == '-1':
            db_result = Order.objects.filter(
                email=email,
                is_delete=0,
            ).all().order_by('-create_time')
            print('全部')
        else:
            db_result = Order.objects.filter(
                email=email,
                is_delete=0,
                pay_status=pay_status
            ).all().order_by('-create_time')

        print(db_result)
        # 序列化
        ser_result = OrederManySerializer(db_result, many=True)
        return ResponseMessage.OrderResponse.success(ser_result.data)